package com.sinosoft.dsp.platform.components.portal.input;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.primefaces.model.SortOrder;

import com.sinosoft.builder.templates.concept.AttributeType;
import com.sinosoft.builder.templates.concept.ResultType;
import com.sinosoft.builder.templates.concept.SelectElementType;
import com.sinosoft.builder.templates.concept.SqlConfigType;
import com.sinosoft.builder.templates.concept.TagElementType;
import com.sinosoft.dsp.persistence.hibernate.dao.CommonDao;
import com.sinosoft.dsp.platform.components.portal.iteration.DataTableHeaderObject;
import com.sinosoft.dsp.platform.components.portal.iteration.RowDataTableObject;
import com.sinosoft.dsp.platform.components.portal.iteration.SinoAbstractLazyRowDataTableViewBean;
import com.sinosoft.dsp.platform.exception.SinoPlatformException;
import com.sinosoft.dsp.platform.services.CodeSetService;
import com.sinosoft.dsp.platform.services.SearchFormService;
import com.sinosoft.dsp.platform.utils.SinoManagedBean;
import com.sinosoft.dsp.system.core.log.Log;
import com.sinosoft.dsp.system.to.IGenericTO;
import com.sinosoft.dsp.system.utils.Const;
import com.sinosoft.dsp.system.utils.ReflectionUtils;

public class SinoSearchFormDataViewBean extends
		SinoAbstractLazyRowDataTableViewBean implements
		ISinoSearchFormDataViewBean {

	private static final Log log = Log.getLog(SinoSearchFormDataViewBean.class
			.getName());

	private String sql;

	private String countSql;

	private SqlConfigType sqlConfig;

	private SinoDefaultSearchBean searchBean;

	public SinoSearchFormDataViewBean() {

	}

	public SinoSearchFormDataViewBean(SqlConfigType sqlConfig,
			SinoDefaultSearchBean searchBean) {
		this.sqlConfig = sqlConfig;
		this.searchBean = searchBean;
	}

	@Override
	public void reload() {
		this.sql = null;
		this.setReloadFlag();
	}

	@Override
	public List<DataTableHeaderObject> initHeader(IGenericTO tos) {
		ResultType result = searchBean.getMeta().getResult();
		if (result != null && result.getTagElement() != null) {
			List<DataTableHeaderObject> rtn = new ArrayList<DataTableHeaderObject>();
			DataTableHeaderObject header = null;
			for (TagElementType tag : result.getTagElement()) {
				header = new DataTableHeaderObject(tag.getValue());
				header.setDescription(tag.getTitle()).setSortable(
						tag.isIsSort()).setDisplay(tag.isIsDisplay());
				rtn.add(header);
			}
			return rtn;
		}
		return null;
	}

	@Override
	public List<RowDataTableObject> fetchPage(int first, int pageSize,
			String sortField, SortOrder sortOrder, Map<String, String> filters)
			throws SinoPlatformException {
		try {
			if (sql == null) {
				SearchFormService sfs = SinoManagedBean
						.findBean("searchFormService");
				sql = sfs.getSQLForSearchForm(this.sqlConfig, this.searchBean
						.getConditionFieldsMap());
			}
			log.info("执行分页查询：" + sql);
			CommonDao dao = SinoManagedBean.findBean("commonDao");
//			List<?> result = dao.findByPageForSearchForm(sql, searchBean
//					.getConditionFieldsMap(), first, pageSize);

			// 排序，过滤 TODO
//			List<RowDataTableObject> rows = new ArrayList<RowDataTableObject>();
//			if (result != null) {
//				for (Object r : result) {
//					rows.add(createRow((Object[]) r));
//				}
//			}

			return rows;
		} catch (SinoPlatformException e) {
			throw e;
		} catch (Exception e) {
			throw new SinoPlatformException("分页查询出现错误。");
		}
	}

	@Override
	public int fetchRowCount(String sortField, SortOrder sortOrder,
			Map<String, String> filters) throws SinoPlatformException {
		try {
			if (countSql == null) {
				SearchFormService sfs = SinoManagedBean
						.findBean("searchFormService");
				countSql = sfs.getSQLCountForSearchForm(this.sqlConfig,
						this.searchBean.getConditionFieldsMap());
			}

			log.info("执行查询总行数：" + countSql);

			CommonDao dao = SinoManagedBean.findBean("commonDao");
//			Long count = dao.countForSearchFormByCountSql(countSql, searchBean
//					.getConditionFieldsMap());
//			if (count != null) {
//				return count.intValue();
//			}
			return 0;
		} catch (SinoPlatformException e) {
			throw e;
		} catch (Exception e) {
			throw new SinoPlatformException("分页查询统计总数出现错误。");
		}
	}

	private RowDataTableObject createRow(Object[] r)
			throws SinoPlatformException {
		try {
			ResultType result = searchBean.getMeta().getResult();
			RowDataTableObject row = new RowDataTableObject();
			CodeSetService css = SinoManagedBean.findBean("codeSetService");
			if (result != null && result.getTagElement() != null) {
				for (TagElementType tag : result.getTagElement()) {
					Object c = r[getSelectElementIndex((SelectElementType) tag
							.getRef())];
					String v = "";
					// 根据类型格式化成字符串
					if (c != null) {
						v = tag2Str(c, tag);
						if (!Const.isEmpty(tag.getBeanClassName())
								&& !Const.isEmpty(tag.getBeanMethod())) {
							Object bean = SinoManagedBean.findBean(tag
									.getBeanClassName());
							v = (String) ReflectionUtils.invokeMethod(bean, tag
									.getBeanMethod(), tag, v);
						} else if (!Const.isEmpty(tag.getCodeSetId())) {
							v = css.getCodeName(tag.getCodeSetId(), v.trim());
						}
					}
					row.addRow(v);
				}
			}

			return row;
		} catch (SinoPlatformException e) {
			throw e;
		} catch (Exception e) {
			throw new SinoPlatformException("创建行记录出现错误。");
		}
	}

	private String tag2Str(Object c, TagElementType tag) {
		if (c instanceof Character) {
			return ((Character) c).toString();
		} else if (c instanceof Character[]) {
			String rtn = "";
			for (Character tc : ((Character[]) c)) {
				rtn += tc;
			}
			return rtn;
		} else if (c instanceof java.util.Date) {
			DateFormat dateFormat;
			if (tag.getAttributeType() == AttributeType.DATE) {
				dateFormat = new SimpleDateFormat(Const.GENERALIZED_DATE_FORMAT);
			} else if (tag.getAttributeType() == AttributeType.TIME) {
				dateFormat = new SimpleDateFormat(Const.GENERALIZED_TIME_FORMAT);
			} else {
				dateFormat = new SimpleDateFormat(
						Const.GENERALIZED_DATE_TIME_FORMAT);
			}
			return dateFormat.format((java.util.Date) c);
		}
		return String.valueOf(c);
	}

	private int getSelectElementIndex(SelectElementType selectElementType)
			throws SinoPlatformException {
		try {
			List<SelectElementType> setList = this.sqlConfig.getSelect()
					.getSelectElement();
			for (int i = 0; i < setList.size(); i++) {
				if (setList.get(i).getId().equals(selectElementType.getId())) {
					return i;
				}
			}
		} catch (Exception e) {
			throw new SinoPlatformException("通过ID无法找到对应的查询结果，ID："
					+ selectElementType.getId());
		}
		throw new SinoPlatformException("通过ID无法找到对应的查询结果，ID："
				+ selectElementType.getId());
	}
}
